package cn.kgc.kgde.bookstore.controller;

import cn.kgc.kgde.bookstore.dto.CartDTO;
import cn.kgc.kgde.bookstore.entity.*;
import cn.kgc.kgde.bookstore.service.BookService;
import cn.kgc.kgde.bookstore.service.CartitemService;
import cn.kgc.kgde.bookstore.service.OrderService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import cn.kgc.kgde.bookstore.config.AliPayConfig;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;

import com.alipay.easysdk.factory.Factory;
import com.sun.org.apache.xpath.internal.operations.Or;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xiaodai
 * @create 2022-06-15 14:29
 */
@RestController
@RequestMapping("/alipay")
public class AliPayController {
    @Resource
    private OrderService orderService;
    @Resource
    AliPayConfig aliPayConfig;
    private static final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    private static final String FORMAT ="JSON";
    private static final String CHARSET ="utf-8";
    private static final String SIGN_TYPE ="RSA2";
    private final String RETURN_URL = "http://localhost:8085/#/personal";//传值  -- 前台页面完整路径 -- 我的订单

    @Resource
    private BookService bookService;
    @Resource
    private CartitemService cartitemService;
    @PostMapping("/pay") // &subject=xxx&traceNo=xxx&totalAmount=xxx
    public ResultInfo pay(AliPay aliPay, HttpServletResponse httpResponse,Order order,Long  cartId,String userCode) throws Exception {
        /**
         * 生成订单
         */
        System.out.println("cartId = " + cartId);
        System.out.println("userCode = " + userCode);
        System.out.println("order = " +order);
        List<CartDTO> carts =this.orderService.cartDTOList(order,userCode);
        Order order1= this.orderService.add(order,carts);
        //生成订单后修改库存
        Book book = new Book();
        Integer stock = 0;
        //根据购物详情循环修改商品
        for (CartDTO record : carts) {
            book.setId( record.getBookId() );
            Book bookById = this.bookService.findById( book.getId() );
            System.out.println(bookById);
            stock = bookById.getStock()-record.getQuantity();
            bookById.setStock( stock );
            //修改商品库存
            this.bookService.modify( bookById);
//            book.setStock( record.getQuantity() );
//            System.out.println("book = " + book);
        }
        Cartitem cartitem = new Cartitem();
        cartitem.setCartId(cartId);
        this.cartitemService.deleteById(cartitem);

        aliPay.setSubject(order1.getOrderId());
        aliPay.setTraceNo(order1.getOrderId());
        aliPay.setTotalAmount(Double.toString(order1.getTotalCost()));
        /**
         * 结束
         */
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(), FORMAT, CHARSET, aliPayConfig.getAlipayPublicKey(), SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        request.setBizContent("{\"out_trade_no\":\"" + aliPay.getTraceNo() + "\","
                + "\"total_amount\":\"" + aliPay.getTotalAmount() + "\","
                + "\"subject\":\"" + aliPay.getSubject() + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + CHARSET);
        return  new ResultInfo(200,"支付",form);// 返回支付页面
//        httpResponse.getWriter().write(form);// 直接将完整的表单html输出到页面
//        httpResponse.getWriter().flush();
//        httpResponse.getWriter().close();
    }

    @PostMapping("/notify")  // 注意这里必须是POST接口
    public String payNotify(HttpServletRequest request) throws Exception {
        if (request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            System.out.println("=========支付宝异步回调========");
            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
                // System.out.println(name + " = " + request.getParameter(name));
            }
            //订单表的订单编码
            String orderId = params.get("orderId");
            //支付时间
//            String gmtPayment = params.get("gmt_payment");
            //支付交易号
//            String alipayTradeNo = params.get("trade_no");
            // 支付宝验签
            if (Factory.Payment.Common().verifyNotify(params)) {
                // 验签通过
//                System.out.println("交易名称: " + params.get("subject"));
//                System.out.println("交易状态: " + params.get("trade_status"));
//                System.out.println("支付宝交易凭证号: " + params.get("trade_no"));
//                System.out.println("商户订单号: " + params.get("out_trade_no"));
//                System.out.println("交易金额: " + params.get("total_amount"));
//                System.out.println("买家在支付宝唯一id: " + params.get("buyer_id"));
//                System.out.println("买家付款时间: " + params.get("gmt_payment"));
//                System.out.println("买家付款金额: " + params.get("buyer_pay_amount"));

                // 更新订单为已支付
//                ordersMapper.updateState(orderId, "已支付");
                //修改订单状态  -- 传值说明 订单编号  订单状态  （1=》订单已支付还未发货）
                this.orderService.modify( orderId,1 );

            }
        }
        return "success";
    }
}
